package api.service;

import api.model.ApiAuthinfo;
import com.alibaba.fastjson.JSONObject;
import m.common.model.util.ModelCheckUtil;
import m.common.model.util.ModelUpdateUtil;
import m.common.service.Service;
import m.system.cache.CacheUtil;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.url.UrlMarker;
import m.system.util.GenerateID;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;
import manage.model.AdminLogin;

import java.util.Date;

public class ApiAuthinfoService extends Service {

    public String save(ApiAuthinfo model) throws Exception {
        String msg;
        TransactionManager tm=new TransactionManager();
        try {
            tm.begin(model.getOid());
            ModelCheckUtil.checkNotNull(model, "name","authId","authKey","admin.oid","org.oid");
            ModelCheckUtil.checkUniqueCombine(model,new String[]{"authId"});
            if(StringUtil.isSpace(model.getOid())){
                model.setOid(GenerateID.generatePrimaryKey());
                model.setStatus("0");
                ModelUpdateUtil.insertModel(model);
                msg="保存成功";
            }else{
                ModelUpdateUtil.updateModel(model, "description","name","admin.oid","org.oid","authId","authKey","authTime","type");
                msg="修改成功";
            }
            CacheUtil.clear(ApiAuthinfo.class,model.getAuthId());
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
        return msg;
    }

    /**
     * 获取鉴权信息，可自行验证
     */
    public ApiAuthinfo get(String authId){
        return CacheUtil.get(ApiAuthinfo.class,authId);
    }
    /**
     * auth鉴权  返回admin并填充admin.orgGroup
     * auth 按空格分割后['auth',authid,timelong,to32Md5(timelong+authid+authkey)]
     */
    public AdminLogin auth(String auth,String type,boolean isThrow) throws MException {
        try{
            return auth(auth,type);
        }catch (Exception e){
            if(isThrow) throw e;
            else return null;
        }
    }
    private AdminLogin auth(String auth,String type) throws MException {
        ApiAuthinfo a=verifyAuth(auth,type);
        AdminLogin admin=CacheUtil.get(AdminLogin.class,a.getAdmin().getOid());
        admin=JSONObject.parseObject(ObjectUtil.toString(admin),AdminLogin.class);
        admin.setOrgGroup(a.getOrg());
        return admin;
    }

    public String getToken(String timelong,String authId,String authKey){
        return authId+" "+timelong+" "+StringUtil.to32MD5(timelong+authId+authKey);
    }
    /**
     * 验证api鉴权 返回api鉴权信息
     * auth 按空格分割后['auth',authid,timelong,to32Md5(timelong+authid+authkey)]
     */
    public ApiAuthinfo verifyAuth(String auth,String type) throws MException {
        String[] arr = auth.split(" ");//['auth',authid,timelong,to32Md5(timelong+authid+authkey)]
        if (arr.length < 4) throw new MException(this.getClass(),"auth参数错误");
        if(!UrlMarker.isAuth(arr[0])) throw new MException(this.getClass(),"auth前缀错误");
        ApiAuthinfo a=get(arr[1]);
        if(null==a) throw new MException(this.getClass(),"没有鉴权信息");
        if(!type.contains(a.getType())) throw new MException(this.getClass(),"鉴权信息不支持");
        String token=StringUtil.to32MD5(arr[2]+a.getAuthId()+a.getAuthKey());
        if(!arr[3].equals(token)) throw new MException(this.getClass(),"鉴权错误");
        long time=Long.parseLong(arr[2]);
        long now=new Date().getTime();
        if(a.getAuthTime().equals("0")){}//0代表不限制
        else if(Long.parseLong(a.getAuthTime())*1000L<Math.abs(time-now)) throw new MException(this.getClass(),"鉴权超时");
        return a;
    }
}
